// 处理与Student有关的请求

const express = require('express');

// 相对于当前文件所在目录来确定被引入模块的路径
const studentSchema = require('../schemas/student-schema.js');
const mongoDababase = require('../db/mongo-database.js');

const studentRouter = express.Router();

studentRouter.get('/list', (req, resp) => {
    console.log(req.method, req.url);
    let promise = mongoDababase.list('Student', studentSchema);
    promise.then(function(results) {

        let data = {
            students: results
        }

        // 第一个参数表示模板名称
        resp.render('list', data);
    });

});

studentRouter.get('/add', (req, resp) => {
    // 第一个参数表示模板名称
    resp.render('add', {});
});

studentRouter.post('/add', (req, resp) => {
    let params = req.body;
    console.log(params);
    mongoDababase.save('Student', studentSchema, params);
    resp.redirect('/student/list');
});

studentRouter.get('/remove/:id', (req, resp) => {
    let id = req.params.id; // 取路由路径中包含的参数
    console.log(id);

    let promise = mongoDababase.delete('Student', studentSchema, id);
    promise.then(function(results) {
        resp.redirect('/student/list');
    });

});

// 将 studentRouter 直接导出
module.exports = studentRouter;